// pages/sub_specific/sub_specific.js
import * as search from '../../component/search/search';
import {
  getStorage,
  setStorage
} from '../../utils/util';
import Toast from '../../miniprogram_npm/@vant/weapp/lib/toast/toast';


const dbU = wx.cloud.database().collection('User')
const dbM = wx.cloud.database().collection('Main')
const dbT = wx.cloud.database().collection('Top')
const db  = wx.cloud.database()
const _   = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    A: true,
    submit_disable: false,

    selected_subname: "",
    selected_subimg: "",
    // selected_subcolor: "",

    vol_pic_url: "",
    vol_name: "",
    vol_basedInfo: "",
    show_all_volunteers: [],

    // isTop:false, //是否为置顶问题 默认：不是
    topList: [],
    toptopList: [],
    allQuestionList: [],
    solvedQuestionList: [],
    unsolvedQuestionList: [],
    currentQuestionList: [],
    //添加问题
    question_title: '',
    question_describe: '',
    contact_ways: '',
    checked: false, //是否 个性辅导 默认：否
    contact_ways_isHidden: true, //隐藏 输入联系方式
    sms_checked: false,//是否发送短信给义工 默认：否
    sms_isHidden: true,//隐藏输入手机号码 默认：是
    sms_phone_number: '',

    fileList: [],
    img: [],
    // 添加图片 选择义工姓名
    vol_name: "",
    all_vol_name: ['全部'],
    all_vol_openid: [],
    picked_vol_name: '', //被选中的义工名字
    picker_vol_openid: [],
    picker_vol_phone: [],//被选中义工的手机号
    all_vol_phone: [],

    selected_vol_name: '',
    selected_vol_basedInfo: '',
    selected_vol_pic_url: '',
    selected_vol_openid: '',
    selected_vol_solved: 0,
    selected_vol_zan: 0,
    selected_vol_introduction: '这位义工还没有填写自我介绍哦~',

    selected_vol_picker_index: 0, //选择义工picker 选中的内容的index


    add_question_isShow: false, //添加问题图标
    vol_intro_isShow: false,
    // selected_question_isShow: false,
    put_question_isShow: false, //添加问题
    // solved_question_list_isShow: false,
    choose_vol_picker_isShow: false, //添加问题时 选择义工 的选择器是否出现

    // 复选框
    solved_question_checked: true,
    unsolved_question_checked: true,
    question_list_type: '0',//由复选框确定的问题类型: 0所有 1未解决 2已解决

    // 复选框图片路径
    activeIcon: "/icons/selected.png",
    inactiveIcon: "/icons/unselected.png",

  },
    dtConvert(myDate){
    let year=myDate.getFullYear();
    let month=myDate.getMonth();
    let date=myDate.getDate();
    let hour=myDate.getHours();
    let minute=myDate.getMinutes();
    //Date1,年月日
    let Date1=year*10000+(month+1)*100+date;
    //Time,时和分
    let Time=hour*100+minute;
    //DateTime年月日时分
    let DateTime=year*100000000+(month+1)*1000000+date*10000+hour*100+minute;
    return {Date:Date1,Time:Time,DateTime:DateTime};
  },

  //给每个义工发送消息
  send_message: function (a, b) {
    for (let i = 0; i < a.length; i++) {
      db.collection('Message').add({
        data: {
          id: a[i],
          postid: b
        },
        success: function (res) {
          console.log(res)
        }
      })
    }
  },
  // 获取用户openid
  getOpenid() {
    let that = this;
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        console.log('云函数获取到的openid: ', res.result.openId)
        var openid = res.result.openId;
        that.setData({
          openid: openid
        })
        this.refresh()
      }
    })
  },

  getVol: function () {

    // 初次加载页面时 这个函数 没有任何作用 show_all_volunteers就是那6个义工的数据
    // for(var i = 0;i < this.data.show_all_volunteers.length;i++){
    //   console.log('循环获取', this.data.show_all_volunteers[i])
    // }

    dbU.skip(this.data.show_all_volunteers.length).where({
      sub: this.data.selected_subname
    }).get().then(res => {
      console.log(res)
      if (res.data.length != 0) {
        let newvoldata = this.data.show_all_volunteers.concat(res.data)
        this.setData({
          show_all_volunteers: newvoldata
        })
        //构建义工名称&openid的数组
        for (let i = 0; i < res.data.length; i++) {
          let all_vol_name = this.data.all_vol_name
          let all_vol_openid = this.data.all_vol_openid
          let all_vol_phone = this.data.all_vol_phone
          all_vol_name.push(res.data[i].name)
          // TODO 很有可能是这里 
          all_vol_openid.push(res.data[i]._openid)

          var phone_ = res.data[i].phoneNumber
          var phone_forbidden_ = res.data[i].phone_forbidden
          if(phone_===undefined)phone_=''//手机号未填写则置空
          if(phone_forbidden_ != undefined && phone_forbidden_ == true)phone_=''//不允许发短信则置空
          all_vol_phone.push(phone_)
          this.setData({
            all_vol_name,
            all_vol_openid,
            all_vol_phone
          })
        }
        console.log('all_vol_openid:' + this.data.all_vol_openid)
        this.getVol()
      }

    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '请稍等',
      mask: true
    })
    this.selectComponent('#tabs').resize();
    this.setData({
      selected_subname: options.selected_subname,
      selected_subimg: options.selected_subimg,
    })
    //获取义工列表
    dbU.where({
      sub: this.data.selected_subname
    }).get().then(res => {
      console.log("义工列表：")
      console.log(res)
      this.setData({
        show_all_volunteers: res.data
      })
      //构建义工名称&openid的数组
      for (let i = 0; i < this.data.show_all_volunteers.length; i++) {
        let all_vol_name = this.data.all_vol_name
        let all_vol_openid = this.data.all_vol_openid
        let all_vol_phone = this.data.all_vol_phone
        all_vol_name.push(this.data.show_all_volunteers[i].name)
        all_vol_openid.push(this.data.show_all_volunteers[i]._openid)
        var phone_ = this.data.show_all_volunteers[i].phoneNumber
        var phone_forbidden_ = this.data.show_all_volunteers[i].phone_forbidden
        if(phone_===undefined)phone_=''//手机号未填写则置空
        if(phone_forbidden_ != undefined && phone_forbidden_ == true)phone_=''//不允许发短信则置空
        all_vol_phone.push(phone_)
        this.setData({
          all_vol_name,
          all_vol_openid,
          all_vol_phone
        })
      }
      console.log("所有义工的手机号：")
      console.log(this.data.all_vol_phone)
    }).then(res => {
      //console.log('getVol之前')
      this.getVol()
    })
    this.getOpenid()

    //初始渲染-读取storage的历史记录
    search.init(this)
  },

  goSearch() {
    this.setData({
      wx: wx.navigateTo({
        url: '../search_newPage/search_newPage?selected_subname=' + this.data.selected_subname
      })
    })
  },

    //刷新问题Main中的可接单义工列表 解决新注册义工的接单问题 
  refreshAnsInMain: function () {
    // //获取到的问题榜中刷新可接单义工名单
    // var allQuestionList_ = this.data.allQuestionList
    // //遍历所有问题
    // for(var i=0;i<allQuestionList_.length;i++){
    //   //仅当问题中的可接单义工数量大于一刷新（若等于一则是选定特定义工，不必刷新）
    //   if(allQuestionList_[i].ans.length>1){
    //     //仅当可接单义工数量小于全体义工时刷新（避免数据库的多次访问）有新义工注册
    //     console.log('asdasdad:',this.data.all_vol_openid.length,allQuestionList_[i].ans.length) 
    //     if(this.data.all_vol_openid.length>allQuestionList_[i].ans.length 
    //       || allQuestionList_[i].ans.length>this.data.all_vol_openid.length){
    //       //更新内存中的问题列表
    //       allQuestionList_[i].ans = this.data.all_vol_openid
    //       //更新问题数据库
    //       db.collection('Main').where({
    //         _id:allQuestionList_[i]._id
    //       }).update({
    //         data:{
    //           ans:this.data.all_vol_openid
    //         }
    //       }).then(res=>{
    //         console.log("刷新可接单义工名单")
    //         console.log(res)
    //       })
    //     }
    //   }
    // }
    // //更新内存中的问题列表
    // this.setData({
    //   allQuestionList: allQuestionList_
    // })
  },

  refresh: function () {

    //获取热门榜
    dbM.orderBy('zan', 'desc').where({
      sub: this.data.selected_subname,
      date:_.gt(this.dtConvert(new Date()).DateTime-1000000)
    }).get().then(res => {
      // console.log("获取热门榜：")
      // console.log(res)
      this.setData({
        topList: res.data
      })
    })

    //获取问题榜
    dbM.orderBy('date', 'desc').where({
      sub: this.data.selected_subname
    }).get().then(res => {
      // console.log("问题榜：")
      // console.log(res)
      this.setData({
        allQuestionList: res.data,
        currentQuestionList: res.data
      })
      //刷新可接单义工名单
      this.refreshAnsInMain()
    })

    // 获取已解决问题榜
    dbM.orderBy('date', 'desc').where({
      sub: this.data.selected_subname,
      state: "solved"
    }).get().then(res => {
      // console.log("已解决问题榜：")
      // console.log(res)
      this.setData({
        solvedQuestionList: res.data
      })
    })

    // 获取未解决问题榜
    dbM.orderBy('date', 'desc').where({
      sub: this.data.selected_subname,
      state: "unsolved"
    }).get().then(res => {
      // console.log("未解决问题榜：")
      // console.log(res)
      this.setData({
        unsolvedQuestionList: res.data
      })
    })

    // 重置复选框
    this.setData({
      solved_question_checked: true,
      unsolved_question_checked: true,
    })
    this.changeCurrentQuestionList()
    wx.hideLoading()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      toptopList: []
    })
    //获取置顶榜
    dbT.where({
      sub: this.data.selected_subname
    }).get().then(res => {
      // console.log("置顶榜消息：")
      // console.log(res)
      for (let i = 0; i < res.data[0].top.length; i++) {
        dbM.where({
          _id: res.data[0].top[i]
        }).get().then(res0 => {
          let toptopList = this.data.toptopList
          toptopList.push(res0.data[0])
          this.setData({
            toptopList
          })
        })
      }
    })

    this.refresh()
  },


  // 点击+号 打开 添加问题界面
  add_questions() {
    this.setData({
      add_question_isShow: true,
    })
  },
  //关闭 添加问题界面
  add_question_onClose() {
    this.setData({
      add_question_isShow: false,
      question_title: '',
      question_describe: '',
      checked: '',
      contact_ways: '',
      img: [],
      fileList: [],
      picked_vol_name: "",
    })
  },
  isIndividual_onChange(detail) {
    var checked_ = this.data.checked;
    var contact_ways_isHidden_ = this.data.contact_ways_isHidden;
    if (!checked_) {
      checked_ = true;
      contact_ways_isHidden_ = false;
    } else {
      checked_ = false;
      contact_ways_isHidden_ = true;
    }
    this.setData({
      checked: checked_,
      contact_ways_isHidden: contact_ways_isHidden_
    })
  },

  //发短信按钮
  isSendSms_onChange(){
    var sms_checked_  = this.data.sms_checked
    var sms_isHidden_ = this.data.sms_isHidden
    var sms_phone_number_ = this.data.sms_phone_number
    if (!sms_checked_) {
        sms_checked_  = true;
        sms_isHidden_ = false;
    } else {
      sms_checked_  = false;
      sms_isHidden_ = true;
      sms_phone_number_ = '';
    }
    this.setData({
      sms_checked  : sms_checked_,
      sms_isHidden : sms_isHidden_,
      sms_phone_number : sms_phone_number_,
    })
  },

  //添加图片  添加问题界面
  afterRead(event) {
    let that = this;
    // console.log(event)
    let obj = event.detail

    console.log(obj)
    let NewfileList = {}
    NewfileList.url = obj.file.url
    NewfileList.name = "image" + obj.index
    NewfileList.index = obj.index
    NewfileList.type = 'image'
    NewfileList.size = obj.file.size
    let fileList = []
    fileList.push(...that.data.fileList, NewfileList);
    that.setData({
      fileList
    })
    console.log(that.data.fileList)
  },

  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    }).then(res => {
      console.log(res.fileID)
      let img = []
      img.push(...this.data.img, res.fileID)
      this.setData({
        img
      })
    }).catch(error => {});
  },

  //选择义工的picker弹出
  choose_vol_picker() {
    this.setData({
      choose_vol_picker_isShow: true
    });
  },
  //选择义工的picker关闭
  choose_vol_picker_onClose() {
    this.setData({
      choose_vol_picker_isShow: false
    });
  },


  check: function (e) {
    wx.cloud.callFunction({
      name: 'ContentCheck',
      data: {
        txt: e
      },
      success(res) {
        console.log(e)
        console.log('ContentCheck-res', res)
        if (res.result.errCode == 87014) {
          console.log(res.errCode)
          wx.showToast({
            icon: 'none',
            title: '文字违规',
          })
        }
      },
      fail(err) {
        console.log('ContentCheck-err', err)
        wx.showToast({
          icon: 'none',
          title: '文字违规,发布内容将被删除',
        })
      }
    })


  },
  // 选择义工 添加问题界面
  choose_vol_onConfirm: function (e) {
    const {
      picker,
      value,
      index
    } = e.detail;
    // var picked_vol_name = "${value}";
    // 查找{{selected_vol_name}}是否有值，有值的话对应的index是多少，设置selected_vol_picker_index  ？？？？？？？？
    // 无值则selected_vol_picker_index 为 0
    this.setData({
      picked_vol_name: e.detail.value,
      choose_vol_picker_isShow: false,
    });
    console.log("picker选择器e.detail:" + e.detail);
    console.log("选中的义工是：" + e.detail.value);
  },

  dtConvert(myDate) {
    let year = myDate.getFullYear();
    let month = myDate.getMonth();
    let date = myDate.getDate();
    let hour = myDate.getHours();
    let minute = myDate.getMinutes();
    //Date1,年月日
    let Date1 = year * 10000 + (month + 1) * 100 + date;
    //Time,时和分
    let Time = hour * 100 + minute;
    //DateTime年月日时分
    let DateTime = year * 100000000 + (month + 1) * 1000000 + date * 10000 + hour * 100 + minute;
    return {
      Date: Date1,
      Time: Time,
      DateTime: DateTime
    };
  },


  //发送问题 点击提交按钮
  send_question() {
    this.setData({
      submit_disable: true
    })

    wx.showLoading({
      title: '加载中',
    })

    //暂停两秒
    var start = Date.now();
    while (true) {
      var nowTime = Date.now();
      var offset = nowTime - start;
      if (offset >= 2000)
        break;
    }


    //手机号校验
    var regex = /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
    
    if (this.data.question_title != '' && this.data.question_describe != '' &&
      (this.data.checked == false || (this.data.checked == true && this.data.contact_ways != ''))) {
      //提交问题
      // 获取页面数据????
      let date = new Date(); //当前标准时间格式
      var datenum = this.dtConvert(date).DateTime
      console.log(datenum)

      this.check(this.data.question_title)
      this.check(this.data.question_describe)

      // 上传图片
      wx.cloud.init();
      const {
        fileList
      } = this.data;
      if (!fileList.length) { //无图片
        if (this.data.picked_vol_name == '全部' || this.data.picked_vol_name == '') {
          console.log('全部')
          this.setData({
            picker_vol_openid: this.data.all_vol_openid,
            picker_vol_phone : this.data.all_vol_phone
          })
        } else {
          for (let i = 0; i < this.data.show_all_volunteers.length; i++) {
            if (this.data.picked_vol_name == this.data.show_all_volunteers[i].name) {
              console.log('匹配')
              this.setData({
                picker_vol_openid: [this.data.show_all_volunteers[i]._openid],
                picker_vol_phone : [this.data.all_vol_phone[i]]
              })
            }
          }
        }
        let that_array = this.data.picker_vol_openid
        let that = this
        dbM.add({
          data: {
            ans: this.data.picker_vol_openid,
            date: datenum,
            des: this.data.question_describe,
            checked: this.data.checked,
            contact: this.data.contact_ways,
            phoneNumber:this.data.sms_phone_number,
            img: this.data.img,
            picker: '',
            score: -1,
            state: 'unsolved',
            sub: this.data.selected_subname,
            title: this.data.question_title,
            visible: true,
            zan: 0
          },
          success: function (res) {

            wx.showToast({
              title: '提交成功!୧(๑•̀⌄•́๑)૭',
              icon: 'success',
              duration: 2000 //持续的时间
            })
            console.log('???为什么')
            console.log(that_array)
            that.send_message(that_array, res._id)
            console.log(res)
          }
        })
        this.setData({
          add_question_isShow: false,
          question_title: '',
          question_describe: '',
          checked: false,
          contact_ways: '',
          img: [],
          fileList: [],
          picked_vol_name: "",
          picker_vol_openid: []
        })

        this.setData({
          submit_disable: false
        })

        wx.hideLoading()
      } else { //有图片
        const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`photo/${this.data.openid}-photo${index}${datenum}.png`, file));
        wx.showToast({
          title: '上传中',
          icon: 'loading'
        })
        Promise.all(uploadTasks)
          .then(res => {
            wx.showToast({
              title: '上传成功',
              icon: 'none'
            })

            var start = Date.now();
            while (true) {
              var nowTime = Date.now();
              var offset = nowTime - start;
              if (offset >= 2000)
                break;
            }

            this.setData({
              cloudPath: res,
              fileList: []
            })

            if (this.data.picked_vol_name == '全部' || this.data.picked_vol_name == '') {
              console.log('全部')
              this.setData({
                picker_vol_openid: this.data.all_vol_openid,
                picker_vol_phone : this.data.all_vol_phone
              })
            } else {
              for (let i = 0; i < this.data.show_all_volunteers.length; i++) {
                if (this.data.picked_vol_name == this.data.show_all_volunteers[i].name) {
                  console.log('匹配')
                  this.setData({
                    picker_vol_openid: [this.data.show_all_volunteers[i]._openid],
                    picker_vol_phone : [this.data.all_vol_phone[i]]
                  })
                }
              }
            }
            let that_array = this.data.picker_vol_openid
            let that = this
            dbM.add({
              data: {
                ans: this.data.picker_vol_openid,
                date: datenum,
                des: this.data.question_describe,
                checked: this.data.checked,
                contact: this.data.contact_ways,
                phoneNumber:this.data.sms_phone_number,
                img: this.data.img,
                picker: '',
                score: -1,
                state: 'unsolved',
                sub: this.data.selected_subname,
                title: this.data.question_title,
                visible: true,
                zan: 0
              },
              success: function (res) {
                wx.showToast({
                  title: '提交成功!',
                  icon: 'success',
                  duration: 2000 //持续的时间
                })
                console.log(that_array)
                that.send_message(that_array, res._id)
                console.log(res)
              }
            })
            this.setData({
              add_question_isShow: false,
              question_title: '',
              question_describe: '',
              checked: false,
              contact_ways: '',
              img: [],
              fileList: [],
              picked_vol_name: "",
              picker_vol_openid: []
            })

            this.setData({
              submit_disable: false
            })

            wx.hideLoading()
          })
          .catch(e => {
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
            console.log(e);
          });
      }
      //上传图片结束

      //开始发送短信
      console.log("义工手机号是：")
      console.log(this.data.picker_vol_phone)
      var vol_phone = this.data.picker_vol_phone
      for (let i = 0; i < vol_phone.length; i++) {
        if(vol_phone[i]!=''){
          console.log(vol_phone[i])
          //开始发送短信
          const phone_ = vol_phone[i]
          const subject_ = this.data.selected_subname
          console.log("发给："+phone_+" 科目："+subject_)
          wx.request({
            method:'POST',
            url: getApp().data.root + '/studyaider/sendtoworker',
            header:{
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data:{
              phone  : phone_,
              subject: subject_
            },
            success:function(res){
              console.log(res)
            }
          })//发送短信结束
        }
      }

    } else {
      Toast.fail('还有信息未填写');
      wx.hideLoading()
      this.setData({
        submit_disable: false
      })
    }
    this.refresh()
  },
  //查看问题 问题列表list 热度排行list 义工解决过的问题list
  questions_check_question: function (e) {
    let index = e.currentTarget.dataset.index;
    let t = e.currentTarget.dataset.id;
    let url = "";
    /* 
      根据传入参数确定所在问题列表
      0：所有问题
      1：未解决的问题
      2：已解决的问题
    */
   console.log(t)
    if (t == "0") {
      url = '../post/post?id=' + this.data.allQuestionList[index]._id;
    } else if (t == "1") {
      url = '../post/post?id=' + this.data.unsolvedQuestionList[index]._id
    } else if (t == "2") {
      url = '../post/post?id=' + this.data.solvedQuestionList[index]._id
    }

    // console.log('index:'+index+'title'+this.data.allQuestionList[index].title)
    wx.navigateTo({
      url: url
    })
  },

  topList_check_question: function (e) {
    let index = e.currentTarget.dataset.index;
    wx.navigateTo({

      url: '../post/post?id=' + this.data.topList[index]._id

    })
  },

  toptopList_check_question: function (e) {
    let index = e.currentTarget.dataset.index;
    wx.navigateTo({

      url: '../post/post?id=' + this.data.toptopList[index]._id

    })
  },

  //删除选中的图片
  delete(event) {
    let n = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(n, 1)
    this.setData({
      fileList
    })
  },

  // 查看某个义工详细信息
  check_vol_intro: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      vol_intro_isShow: true,
      selected_vol_name: this.data.show_all_volunteers[index].name,
      selected_vol_basedInfo: this.data.show_all_volunteers[index].class,
      selected_vol_pic_url: this.data.show_all_volunteers[index].url,
      selected_vol_openid: this.data.show_all_volunteers[index]._openid,
      selected_vol_introduction: this.data.show_all_volunteers[index].introduction
    })
    if (this.data.show_all_volunteers[index].introduction == "") {
      this.setData({
        selected_vol_introduction: "这位义工还没有填写自我介绍哦~"
      })
    }

    dbM.where({
      picker: this.data.show_all_volunteers[index]._openid,
      state: _.in(['solved','solving'])
    }).get().then(res => {
      let zzan = 0
      console.log(res.data)
      for (let i = 0; i < res.data.length; i++) {
        zzan = zzan + res.data[i].zan
      }

      this.setData({
        selected_vol_zan: zzan,
        selected_vol_solved: res.data.length
      })
    })
  },
  //关闭弹出层 某个义工详细信息
  vol_intro_onClose() {
    this.setData({
      vol_intro_isShow: false,
      selected_vol_name: '',
      selected_vol_basedInfo: '',
      selected_vol_pic_url: '',
      selected_vol_oopenid: '',
      selected_vol_openid: '',
      selected_vol_solved: 0,
      selected_vol_zan: 0,
    })
  },

  // 查看解决过的问题list  指定义工的
  solved_question_list() {
    var vol_id = this.data.selected_vol_openid;
    var vol_name = this.data.selected_vol_name;
    this.setData({
      vol_intro_isShow: false,
    });
    wx: wx.navigateTo({
      url: '../vol_lst/vol_list?id=' + vol_id + '&name=' + vol_name,
    })
  },

  //提问界面  向指定义工
  put_question_to_selected_vol() {
    this.setData({
      vol_intro_isShow: false,
      add_question_isShow: true,
      picked_vol_name: this.data.selected_vol_name
    })
  },
  //关闭弹出层 关闭提问界面
  // put_question_onClose() {
  //   this.setData({
  //     put_question_isShow: false
  //   })
  // },

  // 根据选择情况更换问题列表
  changeCurrentQuestionList: function() {
    let solvedChecked = this.data.solved_question_checked
    let unsolvedChecked = this.data.unsolved_question_checked
    let question_list_type = this.data.question_list_type
    let currentQuestionList = []
    let that = this
    if (solvedChecked && unsolvedChecked) { // 展示所有问题
      currentQuestionList = that.data.allQuestionList
      question_list_type  = 0
    } else if (solvedChecked && !unsolvedChecked) { // 仅展示已解决问题
      currentQuestionList = that.data.solvedQuestionList
      question_list_type  = 2
    } else if (!solvedChecked && unsolvedChecked) { // 仅展示未解决问题
      currentQuestionList = that.data.unsolvedQuestionList
      question_list_type  = 1
    }
    this.setData({
      currentQuestionList,
      question_list_type
    })
  },
  // 复选框选择问题（未解决、已解决）
  onChange(e) {
    let selectedId = e.currentTarget.id
    if (selectedId == "solved") {
      this.setData({
        solved_question_checked: !this.data.solved_question_checked,
      })
    } else if (selectedId == "unsolved") {
      this.setData({
        unsolved_question_checked: !this.data.unsolved_question_checked,
      })
    }
    this.changeCurrentQuestionList();
  },

  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    Toast.success('刷新成功!');
    this.refresh()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("触底刷新")
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      duration: 1000,
    })
    // 判断复选框情况，确定当前应更新为哪个列表（所有、未解决、已解决）
    let solvedChecked = this.data.solved_question_checked
    let unsolvedChecked = this.data.unsolved_question_checked
    let check = 0
    if (solvedChecked && unsolvedChecked) { // 展示所有问题
      check = 0
    } else if (solvedChecked && !unsolvedChecked) { // 仅展示已解决问题
      check = 1
    } else if (!solvedChecked && unsolvedChecked) { // 仅展示未解决问题
      check = 2
    }
    //获取问题榜
    dbM.orderBy('date', 'desc').skip(this.data.allQuestionList.length).where({
      sub: this.data.selected_subname
    }).get().then(res => {
      console.log("触底刷新问题榜：")
      console.log(res)
      let newdata = this.data.allQuestionList.concat(res.data);
      this.setData({
        allQuestionList: newdata
      })
      this.refreshAnsInMain()
      if (check == 0) {
        this.setData({
          currentQuestionList: newdata
        })
      }
    })
    // 增加已解决问题
    dbM.orderBy('date', 'desc').skip(this.data.solvedQuestionList.length).where({
      sub: this.data.selected_subname,
      state: "solved"
    }).get().then(res => {
      console.log("触底刷新已解决问题榜：")
      console.log(res)
      let newdata = this.data.solvedQuestionList.concat(res.data);
      this.setData({
        solvedQuestionList: newdata
      })
      if (check == 1) {
        this.setData({
          currentQuestionList: newdata
        })
      }
    })
    // 增加未解决问题
    dbM.orderBy('date', 'desc').skip(this.data.unsolvedQuestionList.length).where({
      sub: this.data.selected_subname,
      state: "unsolved"
    }).get().then(res => {
      console.log("触底刷新未解决问题榜：")
      console.log(res)
      let newdata = this.data.unsolvedQuestionList.concat(res.data);
      this.setData({
        unsolvedQuestionList: newdata
      })
      if (check == 2) {
        this.setData({
          currentQuestionList: newdata
        })
      }
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})